package com.lula.cursilho.service;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.annotations.Transactional;

import org.springframework.stereotype.Service;

import com.lula.cursilho.dao.PMF;
import com.lula.cursilho.domain.Cursilho;
import com.lula.cursilho.exceptions.CursilhoException;

@Service("cursilhoService")
public class CursilhoServiceImpl implements CursilhoService{

	PersistenceManagerFactory pmfInstance = PMF.get();
	
	public List<Cursilho> pesquisarTodos() {
		PersistenceManager pm = pmfInstance.getPersistenceManager();
	    String query = "select from " + Cursilho.class.getName();
	    List<Cursilho> list = (List<Cursilho>) pm.newQuery(query).execute();
	    return list;
	}

	public List<Cursilho> pesquisarPorNome(String nome) {
		PersistenceManager pm = pmfInstance.getPersistenceManager();
	    String query = "select from " + Cursilho.class.getName() + " c where c.nome like '" + nome + "%'";
	    List<Cursilho> list = (List<Cursilho>) pm.newQuery(query).execute();
	    return list;
	}

	@Transactional
	public void gravarCursilho(Cursilho cursilho) throws CursilhoException{
		PersistenceManager pm = pmfInstance.getPersistenceManager();
		try {
			pm.makePersistent(cursilho);
		}catch(Exception e){
			throw new CursilhoException("Erro ao gravar cursilho: " + e.getMessage());
		}finally {
			pm.close();
		}
	}
	
	@Transactional
	public void removerCursilho(Cursilho cursilho) throws CursilhoException{
		PersistenceManager pm = pmfInstance.getPersistenceManager();
		try {
			pm.deletePersistent(cursilho);
		}catch(Exception e){
			throw new CursilhoException("Erro ao remover cursilho: " + e.getMessage());
		}finally {
			pm.close();
		}
	}

	public Cursilho buscarPorId(Long id) {
		PersistenceManager pm = pmfInstance.getPersistenceManager();
		try {
			return pm.getObjectById(Cursilho.class, id);
		} finally {
			pm.close();
		}
	}
}